# coding=utf-8
# @app.route('/index')
# def index():
#     return 'index'
# 导入蓝图，使用该蓝图注册路由
from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session


from info import constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu
from flask import render_template


@index_blu.route('/news_list')
def get_news_list():
    # 1.获取参数 cid 分类id 页码 页数
    cid = request.args.get('cid', 1)
    page = request.args.get('page', 1)
    per_page = request.args.get('per_page', 10)
    # 2.校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 3.查询数据
    filter = [News.status == 0]
    if cid != 1:
        filter.append(News.category_id == cid)
    try:
        paginates = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page, per_page, False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(RET.DBERR, errmsg='查询数据库错误')

    # 获取需要的数据
    news_model_list = paginates.items
    total_page = paginates.pages
    current_page = paginates.page

    # 模型转字典
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_dict())

    data = {
        'news_dict_li': news_dict_li,
        'total_page': total_page,
        'current_page': current_page
    }
    return jsonify(errno=RET.OK, errmsg='OK', data=data)


@index_blu.route('/')
@user_login_data
def index():
    # # 一.用户登录
    # # 1.从session中获取user_id
    # user_id = session.get('user_id')
    # user = None
    # # 2.如果有user_id 查询数据库
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    # 二.点击排行
    # 查询数据库--模型列表--转字典--
    news_list_model = []
    try:
        news_list_model = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库失败')

    news_dict_li = []
    for news in news_list_model if news_list_model else []:
        news_dict_li.append(news.to_dict())

    # 三 分类信息
    try:
        categories = Category.query.all()  # 得到的是一个列表
        # [<Category 1>, <Category 2>, <Category 3>, <Category 4>, <Category 5>, <Category 6>]
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库失败')

    # category to dict is {'id': 1, 'name': '最新'}
    categories_dict_li = []
    for category in categories:
        categories_dict_li.append(category.to_dict())

    # 3.如果查询到了,拼接要显示的数据
    data = {
        # to_dict 返回一个字典
        'user': g.user.to_dict() if g.user else None,
        'news_dict_li': news_dict_li,
        'categories_dict_li': categories_dict_li
    }
    return render_template('news/index.html', data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')

